﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;
using System.Web.UI.WebControls;
using System.Threading;

namespace DocumentManager
{
    public partial class MaintainUsers : Form
    {
        public MaintainUsers()
        {
            InitializeComponent();
        }

        private void MaintainUsers_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'trainingCertificationsDataSet.Users' table. You can move, or remove it, as needed.
            //this.usersTableAdapter.Fill(this.trainingCertificationsDataSet.Users);

            
            
            
            //hide all panels, and move all to main location
            pnlNew.Visible = false;
            pnlViewEdit.Visible = false;
            pnlNew.Location = new Point(72, 54);
            pnlViewEdit.Location = pnlNew.Location;

            fillUsersComboBox();
        }

        private void fillUsersComboBox()
        {
            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);
            OleDbCommand com = con.CreateCommand();
            String vSql = @"select User_Name, Man_Number from Users order by User_Name";
            com.CommandText = vSql;
            ArrayList allUsers = new ArrayList();
            try
            {
                con.Open();

                OleDbDataReader reader = com.ExecuteReader();

                //cbUsers.Items.Add(new ListItem("Select", "0"));
                //cbUsers.Items.Add("Select:0");
                allUsers.Add(new ListItem("Select", "0"));
                new ListItem();
                while (reader.Read())
                {
                    //cbUsers.Items.Add(new ListItem(reader[0].ToString(), reader[1].ToString()));
                    //cbUsers.Items.Add(reader[0] + ":" + reader[1]);
                    allUsers.Add(new ListItem(reader[0].ToString(), reader[1].ToString()));
                }
                cbUsers.DisplayMember = "Text";
                cbUsers.ValueMember = "Value";
                cbUsers.DataSource = allUsers;

                reader.Close();
            }
            catch { }
            finally
            {
                con.Close();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //if (!validateInputs()) return;
            if (!validateInputs(txtManNumber.Text, cbFlights, txtName.Text)) return;
            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);
            OleDbCommand com = con.CreateCommand();
            String vSql = @"insert into users (Man_Number, User_Name, Role_ID, Created_Date, Is_Active, Flight) 
                            values (@ManNumber, @UserName, @Role, @CreatedDate, @Is_Active, @Flight)";
            com.CommandText = vSql;

            int testManNumber;
            if (!int.TryParse(txtManNumber.Text, out testManNumber))
            {
                //not an int
                ((Form1)MdiParent).WriteOtherMessage("Please use only integers for the Man Number");
                return;
            }

            com.Parameters.AddWithValue("@ManNumber", testManNumber);

            com.Parameters.AddWithValue("@UserName", txtName.Text);

            //Using default roles for now, until system is built up more
            com.Parameters.AddWithValue("@Role", 1);

            com.Parameters.AddWithValue("@CreatedDate", DateTime.Today);

            com.Parameters.AddWithValue("@Is_Active", true);



            com.Parameters.AddWithValue("@Flight", cbFlights.SelectedItem);

            try
            {
                con.Open();
                int result = com.ExecuteNonQuery();
                clearNewForm();
                //wait a second
                Thread.Sleep(1000);
                fillUsersComboBox();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught.");
                Console.WriteLine("Ex:" + ex.Message);
                Console.WriteLine("M:" + ex.StackTrace.ToString());
            }
            finally
            {
                con.Close();
            }
        }
        private void btnNewCancel_Click(object sender, EventArgs e)
        {
            pnlNew.Visible = false;

        }


        private void clearNewForm()
        {
            cbFlights.SelectedIndex = 0;
            txtManNumber.Text = String.Empty;
            txtName.Text = String.Empty;
            txtRole.Text = String.Empty;

            trainingCertificationsDataSet.Users.AcceptChanges();
            cbUsers.DataSource = trainingCertificationsDataSet.Users;
//            this.usersTableAdapter.Update(this.trainingCertificationsDataSet.Users);
   
        }

        private void clearViewEditForm()
        {
            //reset dropdown box to zero
            cbViewEditFlight.SelectedIndex = 0;
            cbViewEditFlight.Visible = false;

            txtViewEditFlight.ReadOnly = true;
            txtViewEditFlight.Visible = true;

            txtViewEditFlight.Text = String.Empty;
            txtViewEditManNumber.ReadOnly = true;

            txtViewEditManNumber.Text = String.Empty;
            txtViewEditName.Text = String.Empty;
        }

        private void lbCreateNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            pnlNew.Visible = true;
            pnlViewEdit.Visible = false;
        }

        private void updatePanels(String showPanel)
        {
        }

        private void btnViewEditEdit_Click(object sender, EventArgs e)
        {
            //hide the edit button, reposition save button and show 
            btnViewEditSave.Location = btnViewEditEdit.Location;

            //hide the edit button
            btnViewEditEdit.Visible = false;

            //show the save button
            btnViewEditSave.Visible = true;

            //Un-make fields read only
            //txtViewEditManNumber.ReadOnly = false;    //don't allow users to change man number
            txtViewEditName.ReadOnly = false;

            //move the hidde dropdownlist to the textbox location
            cbViewEditFlight.Location = txtViewEditFlight.Location;

            //show the combo box of flights
            cbViewEditFlight.Visible = true;

            //hide the read only flight
            txtViewEditFlight.Visible = false;
        }

        private void cbUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlNew.Visible = false;
            pnlViewEdit.Visible = false;

            //if it is the first item, return no values.
            if (cbUsers.SelectedIndex == 0) { return; }

            //show view panels
            pnlViewEdit.Visible = true;
            
            //clear any data in boxes
            //clearNewForm();

            //we are going into a read only mode, so hide the cb for flights
            cbViewEditFlight.Visible = false;

            String number = cbUsers.SelectedValue.ToString();
            int ManNumber = int.Parse(number);

            String vSql = "Select * from Users where Man_Number = " + ManNumber;

            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);
            OleDbCommand com = con.CreateCommand();
            com.CommandText = vSql;
            try
            {
                con.Open();
                OleDbDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    txtViewEditFlight.Text = reader["Flight"].ToString();
                    txtViewEditManNumber.Text = reader["Man_Number"].ToString();
                    txtViewEditName.Text = reader["User_Name"].ToString();
                    //cbViewEditFlight.SelectedValue = reader["Flight"].ToString();
                    cbViewEditFlight.SelectedItem = reader["Flight"].ToString();
                }
            }
            catch { }

        }

        private void btnViewEditSave_Click(object sender, EventArgs e)
        {
            if (!validateInputs(txtViewEditManNumber.Text, cbViewEditFlight,txtViewEditName.Text)) return;

            int manNumber = int.Parse(txtViewEditManNumber.Text);

            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);
            OleDbCommand com = con.CreateCommand();
            String vSql = @"update users set User_Name = @UserName, Modified_Date = @ModifiedDate,
                            Flight = @Flight where Man_Number = " + manNumber;

            com.CommandText = vSql;

            //com.Parameters.AddWithValue("@ManNumber", manNumber);
            com.Parameters.AddWithValue("@UserName", txtViewEditName.Text);
            com.Parameters.AddWithValue("@ModifiedDate", DateTime.Today);
            com.Parameters.AddWithValue("@Flight", cbViewEditFlight.SelectedItem);
            try
            {
                con.Open();
                int result = com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught.");
                Console.WriteLine("Ex:" + ex.Message);
                Console.WriteLine("M:" + ex.StackTrace.ToString());
            }
            finally
            {
                con.Close();
            }

            //go back to read only
            txtViewEditFlight.Visible = true;
            txtViewEditFlight.Text = String.Empty;
            cbViewEditFlight.SelectedIndex = 0;
            cbViewEditFlight.Visible = false;
            txtViewEditName.ReadOnly = true;
            txtViewEditName.Text = String.Empty;

            btnViewEditSave.Visible = false;
            btnViewEditEdit.Visible = true;

            //reset dropdown selected index to 0
            cbUsers.SelectedIndex = 0;

            //refreshddrb
            fillUsersComboBox();
        }

        private Boolean validateInputs(String pManNumber, ComboBox pFlights, String pName)
        {
            if (pManNumber.Trim().Length == 0)
            {
                ((Form1)MdiParent).WriteOtherMessage("Invalid Man Number.");

                return false;
            }

            if (pFlights.SelectedIndex == 0 || pFlights.SelectedIndex == -1)
            {
                ((Form1)MdiParent).WriteOtherMessage("Please select a flight");
                return false;

            }
            if (pName.Trim().Length == 0)
            {
                ((Form1)MdiParent).WriteOtherMessage("Please enter a name.");
                return false;
            }

            //validate that the man number is an int
            int manNumber;
            Boolean isInt = int.TryParse(pManNumber.Trim(), out manNumber);
            if (!isInt)
            {
                ((Form1)MdiParent).WriteOtherMessage("Please use only integers for the Man Number.");
                return false;
            }

            return true;
        }

        private void ExecuteNonQuery(String vSql)
        {

        }

        private void btnViewEditCancel_Click(object sender, EventArgs e)
        {
            pnlViewEdit.Visible = false;
            //go back to read only
            txtViewEditFlight.Visible = true;
            txtViewEditFlight.Text = String.Empty;
            cbViewEditFlight.SelectedIndex = 0;
            cbViewEditFlight.Visible = false;
            txtViewEditName.ReadOnly = true;
            txtViewEditName.Text = String.Empty;

            btnViewEditSave.Visible = false;
            btnViewEditEdit.Visible = true;

            //reset dropdown selected index to 0
            cbUsers.SelectedIndex = 0;
        }

        private void btnViewEditDelete_Click(object sender, EventArgs e)
        {
            //if (!validateInputs(txtViewEditManNumber.Text, cbViewEditFlight, txtViewEditName.Text)) return;

            int manNumber = int.Parse(txtViewEditManNumber.Text);

            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);
            OleDbCommand com = con.CreateCommand();
            String vSql = @"delete from users where Man_Number = " + manNumber;
            
            com.CommandText = vSql;

            try
            {
                con.Open();
                int result = com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught.");
                Console.WriteLine("Ex:" + ex.Message);
                Console.WriteLine("M:" + ex.StackTrace.ToString());
            }
            finally
            {
                con.Close();
            }

            //go back to read only
            txtViewEditFlight.Visible = true;
            txtViewEditFlight.Text = String.Empty;
            cbViewEditFlight.SelectedIndex = 0;
            cbViewEditFlight.Visible = false;
            txtViewEditName.ReadOnly = true;
            txtViewEditName.Text = String.Empty;

            btnViewEditSave.Visible = false;
            btnViewEditEdit.Visible = true;

            //reset dropdown selected index to 0
            cbUsers.SelectedIndex = 0;

            //refreshddrb
            fillUsersComboBox();
        }
    }
}
